package cn.myjerry.server.demo4;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class WebApp {
	private static ServletContext contxt;
	static {
		// 获取解析工厂
		SAXParserFactory factory = SAXParserFactory.newInstance();
		// 从解析工厂获取解析器
		SAXParser parser = null;
		try {
			parser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		// 加载文档 Decument 解析处理器
		WebHandler web = new WebHandler();
		try {
			parser.parse(
					Thread.currentThread().getContextClassLoader().getResourceAsStream("cn/myjerry/server/demo4/web.xml"),
					web);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		contxt = new ServletContext();
		
		Map<String, String> mapping = contxt.getMapping();
		for(Mapping mapp : web.getMappingList()) {
			List<String> urls = mapp.getUslPattern();
			for(String url : urls) {
				mapping.put(url, mapp.getName());
			}
		}
		
		Map<String, String> servlet = contxt.getServlet();
		for(Entity entity : web.getEntityList()) {
			servlet.put(entity.getName(), entity.getClz());
		}
		
	}
	
	public static Servlet getServlet(String url) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		if((null == url) || ((url.trim()).equals(""))) {
			return null;
		}
		
		String name = contxt.getServlet().get(contxt.getMapping().get(url));
		
		return (Servlet) Class.forName(name).newInstance();
	}
	
}
